<template>
  <el-dropdown ref="dropdown" trigger="click" placement="top-start">
    <div>
      <svg-icon class="search-icon" icon-class="smallBell" />
      <el-badge v-if="messageTotal!==0" :value="messageTotal" :max="99" :hidden="messageTotal===0?true:false" class="item" />
    </div>
    <el-dropdown-menu slot="dropdown" class="newMessage">
      <div>
        <div class="topNav">
          <el-row>
            <el-col :span="12" class="messageLeft">
              <svg-icon class-name="search-icon" icon-class="smallBellColor" />
              <span class="smallBell">新消息提醒 (<span class="messageTotalColor">{{ messageTotal }}</span>条)</span>
            </el-col>
            <el-col :span="1.5">
              <el-button class="blue-btn" type="primary" size="mini" @click="getList">刷新</el-button>
            </el-col>
            <el-col :span="9.5" :offset="1" align="right" class="messageRight">
              <div @click="readMessageAll()">全部标记为已读</div>
            </el-col>
          </el-row>
        </div>
        <div class="messageContent">
          <!-- 全部消息 -->
          <template v-for="(item, index) in messageData">
            <div :key="index" class="messageItem" @click="messageItemClick(item)">
              <div class="hintClass">
                <svg-icon icon-class="hint" />
              </div>
              <div class="messageContentRight">
                <el-row>
                  <el-col :span="16">
                    <span class="topContent">提醒</span>
                  </el-col>
                  <el-col :span="8" class="time">
                    <span>{{ item.createTime }}</span>
                  </el-col>
                </el-row>
                <div class="centerContent">
                  <span v-if="item.msgType === '011'"> 项目分配人员 </span>
                  <span v-if="item.msgType === '012'"> 项目分配设备 </span>
                  <span v-if="item.msgType === '021'"> 钻孔分配人员</span>
                  <span v-if="item.msgType === '022'"> 项目人员分配钻孔</span>
                  <span v-if="item.msgType === '031'"> 钻孔分配设备</span>
                  <span v-if="item.msgType === '032'"> 项目设备分配钻孔</span>
                  <span v-if="item.msgType === '041'"> 人员加入企业</span>
                  <span v-if="item.msgType === '042'"> 企业选择人员</span>
                  <span v-if="item.msgType === '051'"> 监管分配勘察单位</span>
                  <span v-if="item.msgType === '052'"> 勘察单位指定人员</span>
                  <span v-if="item.msgType === '061'"> 责任部门</span>
                  <span v-if="item.msgType === '062'"> 部门分人</span>
                  <span v-if="item.msgType === '071'"> 企业审核</span>
                  <span v-if="item.msgType === '072'"> 用户审核</span>
                  <span>: </span>
                  <span> {{ item.title }} </span>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <MessageItem ref="messageItem" @childrenGetList="childrenGetList" @hide="hide" />
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import MessageItem from './components/index'
import { listReceive, changeAllStatus, changeStatus } from '@/api/PersonalOffice/info'
export default {
  name: 'Message',
  components: {
    MessageItem
  },
  data() {
    return {
      messageTotal: 0, // 全部未读消息条数
      messageData: [] // 全部未读消息
    }
  },
  created() {
    this.getList()
    this.initWebSocket() // 初始化socket连接
  },
  mounted() {
    this.getList()
    // 5000 毫秒 = 5 秒
    // setInterval(() => {
    //   this.getList()
    // }, 10000)
  },
  // 登出当前账号时，断开连接
  destroyed() {
    this.websock.close() // 离开路由之后断开websocket连接
  },
  methods: {
    // 获取消息数据
    async getList() {
      const { data: { rows, total }} = await listReceive({ 'status': '0' })
      this.messageData = rows
      this.messageTotal = total
    },
    // 隐藏消息弹框
    hide() {
      this.$refs.dropdown.hide()
    },
    // 跳转对应的页面并改变消息状态
    async messageItemClick(item) {
      // 清空本地存储
      sessionStorage.removeItem('enterMessage')
      sessionStorage.removeItem('message')
      const mesType = new Map([
        ['011', ['项目分配人员', '/newProject/project-detail']], // x后只发消息不确认
        // ['012', ['项目分配设备', '/newProject/project-detail']],
        ['021', ['钻孔分配人员', '/newProject/exploration-detail']],
        // ['022', ['项目人员分配钻孔', '/PersonalOffice/explorationConfirm']],  注释后不再发消息
        // ['031', ['钻孔分配设备', '/newProject/exploration-detail']],
        // ['032', ['项目设备分配钻孔', '/PersonalOffice/explorationConfirm']],
        ['041', ['人员加入企业', '/PersonalOffice/personalInfo']],
        ['042', ['企业选择人员', '/PersonalOffice/enterpriseInfo']],
        ['051', ['监管分配勘察单位', '/newProject/project-detail']], // x
        ['052', ['勘察单位指定人员', '/newProject/project-detail']], // x
        ['061', ['责任部门', '/newProject/project-detail']], // x
        ['062', ['部门分人', '/newProject/project-detail']], // x
        ['071', ['企业审核', '/personalOffice/enterpriseApproval']],
        ['072', ['用户审核', '/personalOffice/personApproval']],
        ['default', ['首页', '/index']]
      ])
      const content = JSON.parse(item.content)
      content['msgType'] = item.msgType
      content['messageId'] = item.id
      const action = mesType.get(item.msgType) || mesType.get('default')
      if ('explorationId' in content && content.explorationId.length > 1) {
        this.$router.push({ path: '/personalOffice/DrillHole', query: content })
      } else {
        this.$router.push({ path: action[1], query: content })
      }
      await changeStatus({ id: item.id, status: '1' })
      this.getList()
      this.hide()
    },
    // 一键全部标记为已读
    async readMessageAll() {
      const status = '1'
      if (this.messageTotal !== 0) {
        await changeAllStatus(status)
        this.getList()
      }
    },
    /** WebSocket start*/
    initWebSocket() {
      // 初始化weosocket(必须)
      // 当前登录人id
      let userId = this.$store.getters.userInfo.userId
      if (typeof (userId) === 'undefined') { userId = this.$store.getters.sysAccount.id }
      // 请求地址
      const wsuri = 'ws://' + location.host + process.env.VUE_APP_SOCKET_API + '/sys/websocket/' + userId
      // const wsuri = 'ws://192.168.5.116:8080/sys/websocket/' + userId
      this.websock = new WebSocket(wsuri) // 新建一个webstock对象
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    // websocket连接后发送数据(send发送)
    websocketonopen() {
      const actions = '连接成功' // 请根据实际项目需要进行修改
      this.websocketsend(JSON.stringify(actions))
      console.log('WebSocket连接成功')
    },
    // 连接建立失败重连
    websocketonerror() {
      this.initWebSocket()
      // console.log('WebSocket连接失败重连')
    },
    // 数据接收
    websocketonmessage(event) {
      // 将通知消息显示到前台页面
      const resp = JSON.parse(event.data)
      if (resp.type === 'message') {
        this.messageData = resp.message
        this.messageTotal = this.messageData.length
      }
    },
    // 数据发送
    websocketsend(Data) {
      this.websock.send(Data)
    },
    // 关闭
    websocketclose(e) {
      // console.log('断开连接', e)
    },
    /** WebSocket end*/
    childrenGetList() {
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }
  .hintClass{
    cursor: pointer;
    font-size: 26px;
  }
  .item {
   margin-top: -8px;
   margin-left:-15px;
  }
  .menu{
    display:flex;
  }
  .newMessage{
    width:400px;
    height:500px;
    overflow: auto;
    border: solid 1px #aaa;
    .topNav{
      width:100%;height:60px;
      line-height:60px;
      border-bottom:solid 1px #aaa;
      font-size:14px;
      .messageLeft{
        padding-left:10px;
        .smallBell{
          margin:0 10px 0;
        }
        .messageTotalColor {
          color:#ff5857;
        }
      }
      .messageRight{
        padding-right:10px;
        color: #3385ff;
        cursor:pointer;
      }
    }
    .menu{
      width:100%;
      height:60px;
      line-height:60px;
      border-bottom:solid 1px #aaa;
      padding-left:10px;
      padding-right:10px;
    }
  }
  .currentClass{
    background-color:#3385ff !important;
    color:#fff !important;
  }
  .messageItem{
    width:100%;min-width:80px;
    display: flex;
    padding:15px 20px;
    .messageContentRight{
      margin-left:6px;
      width: 100%;
      .topContent{
        font-size:16px;
        color:#3385ff;
      }
      .time{
        color:#666;
        font-size: 14px;
        text-align: right;
      }
      .centerContent{
        margin:5px 0 5px 0 ;
        color:#333;
        font-size: 15px;
      }
    }
    &:hover{
      background: #eee;
      cursor: pointer;
    }
  }
</style>
